package com.dollar.ruyuan_juc.producerConsumer;

import java.util.Queue;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class RequestQueue {

    private Queue<String> queue = new ArrayBlockingQueue(100);
    ReentrantLock lock = new ReentrantLock();
    Condition condition = lock.newCondition();

    public String get() {
        String result = null;
        lock.lock();
        try {
            while (queue.isEmpty()) {
                condition.await();
            }
            result = queue.poll();
            condition.signalAll();
        } catch (InterruptedException e) {
            condition.signalAll();
        } finally {
            lock.unlock();
        }
        return result;
    }

    public void put(String request) {
        lock.lock();
        try {
            while (queue.size() == 100) {
                condition.await();
            }
            queue.offer(request);
            condition.signalAll();
        } catch (InterruptedException e) {
            condition.signalAll();
        } finally {
            lock.unlock();
        }
    }
}
